package com.atues.thread.lock;

public class DeadLock {

    public static void main(String[] args) {
        new MakeUp(0, "小红").start();
        new MakeUp(1, "小明").start();
    }
}
class Lipstick{

}
class Mirror{

}

class MakeUp extends Thread {
    private Lipstick lipstick= new Lipstick();
    private Mirror mirror= new Mirror();


    int choice;
    String girlName;

    MakeUp(int choice, String girlName) {
        super(girlName);
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
        makeup();
    }
    //这段代码是有概率发生死锁的，因为当小红拿到了口红的锁，小明拿到了镜子的锁，小红想要镜子的锁，小明想要口红的锁，这样就会发生死锁
    //改善的时候可以使用锁的顺序来避免死锁，不要同时锁两个对象

    private void makeup(){
        if (choice == 0) {
            synchronized (lipstick) {
                System.out.println(Thread.currentThread().getName() + "获得了口红的锁");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                synchronized (mirror) {
//                    System.out.println(Thread.currentThread().getName() + "获得了镜子的锁");
//                }移到下面
            }

            synchronized (mirror) {
                System.out.println(Thread.currentThread().getName() + "获得了镜子的锁");
            }
        }else {
            synchronized (mirror) {
                System.out.println(Thread.currentThread().getName() + "获得了镜子的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                synchronized (lipstick) {
//                    System.out.println(Thread.currentThread().getName() + "获得了口红的锁");
//                }

            }
            synchronized (lipstick) {
                System.out.println(Thread.currentThread().getName() + "获得了口红的锁");
            }
        }
    }
}
